import { writeFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { DefaultTheme } from 'vitepress';
import { groupBy } from '../../../src/internal/group-by';
import type { RawApiDocsPage } from '../processing/class';
import { formatTypescript } from '../utils/format';
import { FILE_PATH_DOCS } from '../utils/paths';
import { SCRIPT_COMMAND } from './constants';

const pathDocsApiPages = resolve(FILE_PATH_DOCS, '.vitepress', 'api-pages.ts');

/**
 * Writes the api docs index to correct location.
 *
 * @param pages The pages to write into the index.
 */
export async function writePageIndex(pages: RawApiDocsPage[]): Promise<void> {
  const pagesByCategory: Record<string, DefaultTheme.SidebarItem[]> = groupBy(
    pages,
    (page) => page.category ?? '',
    ({ title: text, camelTitle }) => ({ text, link: `/api/${camelTitle}.html` })
  );
  const pageTree = Object.entries(pagesByCategory).flatMap(
    ([category, items]) => (category ? [{ text: category, items }] : items)
  );

  // Write api-pages.ts
  pageTree.unshift({ text: 'Overview', link: '/api/' });
  let apiPagesContent = `
    // This file is automatically generated.
    // Run '${SCRIPT_COMMAND}' to update
    export const apiPages = ${JSON.stringify(pageTree)};
    `.replace(/\n +/, '\n');

  apiPagesContent = await formatTypescript(apiPagesContent);

  writeFileSync(pathDocsApiPages, apiPagesContent);
}
